package com.kungfu.utils;

import java.util.Date;

public class CheckRequestUtils {
    public static boolean check(String timestamp, String sign) {
        byte[] sings = hexStringToBytes(sign);
        String key = MD5Utils.getMD5("xiehe123456");
        System.out.println(key);
        String result = new String(SecretUtils.decryptMode(sings, key));
        return result.equals(timestamp);
    }

    public static String sign(String timestamp) {
        byte[] times = timestamp.getBytes();
        String key = MD5Utils.getMD5("xiehe123456");
        System.out.println(key);

        printHexString(SecretUtils.encryptMode(times, key));
        System.out.println(bytesToHexString(SecretUtils.encryptMode(times, key)));
        String result = new String(SecretUtils.encryptMode(times, key));
        return result;
    }

    public static void main(String[] args) {
//       System.out.println(check("1515141264198", "c83fe801a1d7f033aade8b84217b17b3"));
        String date = new Date().getTime()+"";
        System.out.println(date);
        sign(date);
    }

    //将指定byte数组以16进制的形式打印到控制台
    public static String printHexString(byte[] b) {
        String result = "";
        for (int i = 0; i < b.length; i++) {
            String hex = Integer.toHexString(b[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            result += hex.toUpperCase();
        }

        System.out.println("||||" + result);
        return result;
    }

    public static String bytesToHexString(byte[] src) {
        StringBuilder stringBuilder = new StringBuilder("");
        if (src == null || src.length <= 0) {
            return null;
        }
        for (int i = 0; i < src.length; i++) {
            int v = src[i] & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }

    /**
     * Convert hex string to byte[]
     * @param hexString the hex string
     * @return byte[]
     */
    public static byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }
    /**
     * Convert char to byte
     * @param c char
     * @return byte
     */
    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }
}
